package com.hainatong.shiphelper.mainhome;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.LinearLayout;
import androidx.core.content.ContextCompat;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.SecondActivity;
import com.hainatong.shiphelper.databinding.ActivityWebviewBinding;
import com.hainatong.mvvmbase.base.BaseMvvmActivity;
import com.hainatong.mvvmbase.base.NoViewModel;

import android.app.Activity;
import android.content.Intent;

import android.os.Build;
import android.os.Bundle;

import android.webkit.*;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;


public class WebViewActivity extends BaseMvvmActivity<ActivityWebviewBinding, NoViewModel>
{
    private static String URL_TAG = "WEB_URL";

    private String mUrl;

    private AgentWeb agentWebView;

    public static void start(Activity mContext, String url)
    {
        if(StringUtils.isEmpty( url ))
        {
            start(mContext,null,false);
        }
        else
        {
            Bundle bundle = new Bundle();
            bundle.putString(URL_TAG , url);
            start(mContext,bundle,false);
        }

    }
    public static void start(Activity mContext, Bundle bundle, boolean isFinish)
    {
        Intent intent = new Intent();
        intent.setClass(mContext, WebViewActivity.class);
        if (bundle != null)
            intent.putExtra(mContext.getPackageName(), bundle);
        mContext.startActivity(intent);
        if (isFinish)
        {
            mContext.finish();
        }
    }

    public Bundle getBundle()
    {
        if (getIntent() != null && getIntent().hasExtra(getPackageName()))
            return getIntent().getBundleExtra(getPackageName());
        else
            return null;
    }

    @Override
    protected int getLayoutId()
    {
        return R.layout.activity_webview;
    }

    @Override
    protected int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void initView()
    {
        Bundle mBundle = getBundle();
        if( mBundle != null )
        {
            mUrl = mBundle.getString(URL_TAG,"");
            LogUtils.eTag("WebViewActivity" , mUrl );
        }
        setToolbarTitle(viewDataBinding.includeTitle.toolbar,"");
        setToolBar(viewDataBinding.includeTitle.toolbar);



    }

    @SuppressLint("JavascriptInterface")
    @Override
    protected void initData()
    {
        agentWebView = AgentWeb.with( this )
                               .setAgentWebParent(viewDataBinding.webContent,new LinearLayout.LayoutParams(-1,-1))
                               .useDefaultIndicator(ContextCompat.getColor( this,R.color.green ))
                               .setWebChromeClient( new MyWebChromeClient() )
                               .setWebViewClient( new MyWebViewClient() )
                               .setSecurityType(AgentWeb.SecurityType.DEFAULT_CHECK)
                               .createAgentWeb()
                               .ready()
                               .go(mUrl);

        WebSettings webSettings = agentWebView.getWebCreator().getWebView().getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //        打开页面时， 自适应屏幕：
        //设置此属性，可任意比例缩放 将图片调整到适合webview的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        //支持自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setDatabaseEnabled(true);
        //不设置此 无法加载h5
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);  //支持js调用window.open方法
        webSettings.setJavaScriptEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        // 调用  网页 js 中的 "callJS" 方法
        //agentWebView.getJsAccessEntrace().quickCallJs("callJS");

        // 添加 js 调用 Android 交互方法
        agentWebView.getJsInterfaceHolder().addJavaObject("android", new JavascriptInterface(WebViewActivity.this));
        // 网页 js中 调用  Android 方法
        //window.android.openLink();






        //viewDataBinding.webview.addJavascriptInterface( new JavascriptInterface(WebViewActivity.this), "common" );
        /*
        viewDataBinding.progressbar.setVisibility(View.VISIBLE);
        viewDataBinding.webview.setWebChromeClient( new MyWebChromeClient() );

        //这步就是注册监听你在第一个网站上的点击事件，好进行跳转
        viewDataBinding.webview.setWebViewClient(new MyWebViewClient());

        WebSettings webSettings = viewDataBinding.webview.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(false);

        //        打开页面时， 自适应屏幕：
        webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放 将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        webSettings.setDomStorageEnabled(true); //不设置此 无法加载h5
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);  //支持js调用window.open方法
        webSettings.setJavaScriptEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            viewDataBinding.webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //"https://www.iqiyi.com"
        //mUrl = "file:///android_asset/web/useragreement.html";
        viewDataBinding.webview.addJavascriptInterface( new JavascriptInterface(WebViewActivity.this), "common" );
        viewDataBinding.webview.loadUrl(mUrl);
        */
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (agentWebView.handleKeyEvent(keyCode, event))
        {
            return true;
        }
        return super.onKeyDown(keyCode, event);
        /*
        if ((keyCode == KeyEvent.KEYCODE_BACK) && viewDataBinding.webview.canGoBack())
        {
            //这里是监控点击返回键时，判断这时的页面是否在第一个网址页面，如果不是就一步步的关掉你打开的新网址
            viewDataBinding.webview.goBack();
            return true;
        }
        else
        {
            finish();
            return true;
        }
        */
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void onPause()
    {
        agentWebView.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    protected void onResume()
    {
        agentWebView.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroy()
    {
        agentWebView.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    private void setToolbarTitle(Toolbar toolbar, String title)
    {
        //toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.red));

        ((TextView)toolbar.findViewById(R.id.tv_title)).setText( title );
        ((ImageButton)toolbar.findViewById(R.id.btn_back)).setImageResource(R.drawable.svg_back);
        toolbar.findViewById(R.id.btn_back).setOnClickListener( v -> {
            supportFinishAfterTransition();
        } );
    }


    // 注入js函数监听
    private void addOnClickListner(WebView view)
    {
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        view.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"spot37\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].οnclick=function()  " +
                "    {  "
                + "        window.android.openLink(\"luban://\");  " +
                "    }  " +
                "}" +
                "})()");
    }

// js通信接口

    @SuppressLint("NewApi")
    public class JavascriptInterface
    {

        @SuppressWarnings("unused")
        private Context context;

        public JavascriptInterface(Context context)
        {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void openLink(String url)
        {
            LogUtils.e( "url = " + url );
            //
            SecondActivity.start( this.context );

        }
    }

    public class MyWebChromeClient extends WebChromeClient
    {
        @Override
        public void onReceivedTitle(WebView view, String title)
        {
            super.onReceivedTitle(view, title);
            setToolbarTitle(viewDataBinding.includeTitle.toolbar,title);
            setToolBar(viewDataBinding.includeTitle.toolbar);
        }
        /*
        @Override
        public void onProgressChanged(WebView view, int newProgress)
        {
            if (newProgress == 100)
            {
                //viewDataBinding.progressbar.setVisibility(View.GONE);
            }
            else
            {
                //viewDataBinding.progressbar.setVisibility(View.VISIBLE);
                //viewDataBinding.progressbar.setProgress(newProgress);
            }
        }
        */
        /*
        // For Android >= 5.0
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {

            //Intent intent = fileChooserParams.createIntent();
            //startActivityForResult(intent, CHOOSE_ANDROID_5);
            return true;
        }
        */
    }

    public class MyWebViewClient extends WebViewClient
    {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
        {
            Uri url = request.getUrl();
            LogUtils.eTag("openUrl" , url != null?url.toString(): " = empty url" );

            if (url.toString().startsWith("http://"))
            {
                String content = url.toString().substring("http://".length());
                if (!TextUtils.isEmpty(content))
                {
                    //copy(content);
                }
            }
            try {
                if(url.toString().startsWith("luban://") )
                {
                    //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    //startActivity(intent)
                    return true;
                }
            } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return false;
            }
            //处理http和https开头的url
            //view.loadUrl(url);

            SecondActivity.start( WebViewActivity.this );
            return true;
        }
        /*
       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url)
       {

           view.setWebChromeClient(new MyWebChromeClient());
           view.setWebViewClient(new MyWebViewClient());
           view.getSettings().setJavaScriptEnabled(true);
           view.getSettings().setAppCacheEnabled(true);
           view.getSettings().setAllowFileAccess(true);
           view.getSettings().setUseWideViewPort(true);
           view.getSettings().setLoadWithOverviewMode(true);
           view.getSettings().setDomStorageEnabled(true);
           if (url.startsWith("copy://"))
           {
               String content = url.substring("copy://".length());
               if (!TextUtils.isEmpty(content))
               {
                   //copy(content);
               }
           }
           try {
               if(url.startsWith("luban://") )
               {
                   //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                   //startActivity(intent);
                   SecondActivity.start( WebViewActivity.this );
                   return true;
               }
           } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
               return false;
           }
           //处理http和https开头的url
           view.loadUrl(url);
           return true;

           return super.shouldOverrideUrlLoading(view,url);
       }
       */
        @Override
        public void onPageFinished(WebView view, String url)
        {
            //setToolbarTitle(viewDataBinding.includeTitle.toolbar,view.getTitle());
            //setToolBar(viewDataBinding.includeTitle.toolbar);
            addOnClickListner(view);
        }
    }

}
